import * as React from 'react'
import { Tabs, Toast } from 'antd-mobile'
import { SearchBar, FlatList, Button, Image } from 'components'
import { End } from '../../viewComponent'
import { post, NotBean } from '../../utils'
import anime from 'animejs'
import { ToTop } from '../../viewComponent'
import './index.less'
import { browser } from 'muka'

export default class Detail extends React.Component<any, any> {
    public state = {
        tabs: [],
        goodsData: [],
        viewType: 'horizontal',
        headerStatus: true
    }
    public categoryId: any
    public index: any = 1
    private flNode: any
    private t1: any
    private t2: any
    private scroll = {
        left: 0
    }

    private animate = false

    private historyTop: number = 0

    public componentDidMount() {
        this.getData()
        Toast.loading('加载中...', 0)
        this.initScrollTop()
        window.addEventListener('scroll', this.handleScroll)
    }
    public componentWillUnmount() {
        clearTimeout(this.t1)
        clearTimeout(this.t2)
        window.removeEventListener('scroll', this.handleScroll)
    }

    public render(): JSX.Element {
        const { tabs, viewType, headerStatus } = this.state
        const horizontal = require('../../assets/classfy.png')
        const vertical = require('../../assets/classfy_v.png')
        const { categoryThirdList, categoryThirdIndex } = this.props
        return (
            <React.Fragment>
                <div className="detail">
                    <div style={{ height: '2.5rem' }}>
                        <SearchBar
                            className={`detail_search detail_search_default${this.animate ? headerStatus ? ' show' : ' hide' : ''}`}
                            right={<img className="detail_classfy" onClick={this.handleTabView} src={viewType === 'horizontal' ? horizontal : vertical} />}
                            disabled={true}
                            onPress={() => {
                                this.goToUrl('/search')
                            }}
                        />
                    </div>
                    <div className="tabs__label">
                        <Tabs
                            tabs={tabs}
                            swipeable={false}
                            initialPage={categoryThirdIndex}
                            onTabClick={(tab: any, index) => { this.handleTab(tab.id, index) }}
                            renderTabBar={(props: any) => {
                                return (
                                    <Tabs.DefaultTabBar {...props} animated={false} />
                                )
                            }}
                            prerenderingSiblingsNumber={0}
                            tabBarActiveTextColor="#fa0000"
                        >
                            {
                                tabs.map((data: any, i: number) => {
                                    return (
                                        <div className="detail_tabs_item" key={i}>
                                            <FlatList
                                                ref={(ref) => { this.flNode = ref }}
                                                data={categoryThirdList}
                                                ListEmptyComponent={NotBean}
                                                renderItem={(item, index) => {
                                                    if (viewType === 'horizontal') {
                                                        return (
                                                            <div className="detail_item flex" key={index} onClick={() => { this.goToUrl('/shopDetail/' + item.id) }}>
                                                                <div className="detail_item__img">
                                                                    <Image src={item.pic} loadingIndicatorSource={require('../../assets/bg_img.png')} />
                                                                </div>

                                                                <div className="detail_item_info flex_1 divider">
                                                                    <div className="detail_item_info__title">{item.name}</div>
                                                                    <div className="detail_item_info__number flex">
                                                                        <span className="DINPro flex_justify">¥ {item.price}+{item.price_q}</span>
                                                                        <span className="hendou flex_justify">恒豆</span>
                                                                        <div className="">
                                                                            {
                                                                                this.getTags(item.tags)
                                                                            }
                                                                        </div>
                                                                    </div>
                                                                    <div className="detail_item_info__label">{item.sale_number}人已购买</div>
                                                                </div>
                                                            </div>
                                                        )
                                                    } else {
                                                        return (
                                                            <div className="detail_item vertical" key={index} onClick={() => { this.goToUrl('/shopDetail/' + item.id) }}>
                                                                <div className="detail_item__img">
                                                                    <Image src={item.pic} loadingIndicatorSource={require('../../assets/bg_img.png')} />
                                                                </div>
                                                                <div className="detail_item_info flex_1 ">
                                                                    <div className="detail_item_info__title">{item.name}</div>
                                                                    <div className="detail_item_info__number flex">
                                                                        <span className="DINPro">¥ {item.price}+{item.price_q}</span><span className="hendou">恒豆</span>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        )
                                                    }
                                                }}
                                                onRefresh={this.getGoodsDataScrollLoad}
                                            />
                                            <End />
                                        </div>
                                    )
                                })
                            }
                        </Tabs>
                    </div>
                    {/* <div className="detail_interest flex_center">
                    <img src={require('../../assets/zhuanti.png')} />
                </div> */}
                    {/* <Gird className="detail_gird">
                    <div>
                        <Image className="detail_gird__logo" src={require('../../assets/detail_01.png')} />
                        <div className="detail_gird__title flex_justify">运动户外 狂欢3天开始啦！</div>
                    </div>
                    <div>
                        <Image className="detail_gird__logo" src={require('../../assets/detail_02.png')} />
                        <div className="detail_gird__title flex_justify">轻奢盛夏折扣季 大牌包新色海量上新！</div>
                    </div>
                </Gird> */}
                </div>
                <ToTop />
            </React.Fragment>
        )
    }

    private handleScroll = () => {
        const tops = document.documentElement.scrollTop || document.body.scrollTop
        const dom: any = document.querySelector('.am-tabs-tab-bar-wrap')
        if (tops > 200) {
            this.animate = true
            this.setState(
                {
                    headerStatus: false
                },
                () => {
                    const className = dom.className.split(' ')
                    if (className.includes('show')) {
                        className.pop()
                    }
                    if (!className.includes('hide')) {
                        className.push('hide')
                        dom.className = className.join(' ')
                    }
                }
            )
        } else {
            if (!this.animate) {
                return
            }
            this.setState(
                {
                    headerStatus: true
                },
                () => {
                    const className = dom.className.split(' ')
                    if (className.includes('hide')) {
                        className.pop()
                    }
                    if (!className.includes('show')) {
                        className.push('show')
                        dom.className = className.join(' ')
                    }
                }
            )
        }
        if (this.historyTop > tops && tops > 200 && this.animate) {
            this.setState(
                {
                    headerStatus: true
                },
                () => {
                    const className = dom.className.split(' ')
                    if (className.includes('hide')) {
                        className.pop()
                    }
                    if (!className.includes('show')) {
                        className.push('show')
                        dom.className = className.join(' ')
                    }
                }
            )
        }
        this.historyTop = tops
    }

    private initScrollTop = () => {
        let sessionTop: any = window.sessionStorage.getItem('categoryTabsScrollTop')
        if (!sessionTop) {
            return
        }
        const global: any = window
        const scrollTop = JSON.parse(sessionTop)
        this.t1 = setTimeout(() => { if (global.scrollTo) { global.scrollTo(0, scrollTop) } else { global.screenTop = scrollTop } }, 300)
    }
    private getData = () => {
        const id = this.props.match.params.id
        if (!id) {
            this.goToUrl('/')
            return
        }
        post('goodsapi/goodsCategoryVis', {
            id: this.props.match.params.id
        }).then((data: any) => {
            Toast.hide()
            data = data.map((item: any, index: number) => {
                item.title = item.name
                return item
            })
            this.setState({ tabs: data }, () => { this.initGoods(data) })
        })
    }
    private initGoods = (data: any) => {
        const { categoryThirdIndex } = this.props
        if (data.length > 0) {
            this.categoryId = data[categoryThirdIndex].id
            this.getGoodsDataScrollLoad()
        }
    }
    private getTags = (data: any) => {
        if (!data) {
            return null
        }
        let temp = data.split(',')
        return temp.map((item: any, i: number) => {
            return (
                <Button key={i} className="btn" tick={false}>{item}</Button>
            )
        })
    }
    private getGoodsDataScrollLoad = () => {
        if (!this.categoryId) {
            return
        }
        const { SET_DETAIL_CATEGORYTHIRDLIST, categoryThirdList } = this.props
        post('searchapi/cateGoodsList', {
            category_id: this.categoryId,
            page: this.index,
        }).then((data: any) => {
            if (this.index === 1) {
                SET_DETAIL_CATEGORYTHIRDLIST(data.data)
            } else {
                if (data.data.length) {
                    const temp = JSON.parse(JSON.stringify(categoryThirdList))
                    SET_DETAIL_CATEGORYTHIRDLIST(temp.concat(data.data))
                }
                this.flNode.finishLoad()
            }
            this.index++
            setTimeout(
                () => {
                    const dom = document.querySelector('.tabs__label .am-tabs-default-bar')
                    const active = document.querySelector('.tabs__label .am-tabs-default-bar .am-tabs-default-bar-tab-active')
                    if (dom && active) {
                        const width = browser.width
                        const client = active.getBoundingClientRect()
                        anime({
                            targets: this.scroll,
                            left: dom.scrollLeft - width / 2 + client.width / 2 + client.left,
                            easing: 'linear',
                            duration: 150,
                            update: () => {
                                if (dom.scrollTo) {
                                    dom.scrollTo(this.scroll.left, 0)
                                } else {
                                    dom.scrollLeft = this.scroll.left
                                }
                            }
                        })
                        // dom.scrollTo(dom.scrollLeft - width / 2 + client.width / 2 + client.left, 0)
                    }
                },
                200)
        })
    }
    private handleTab = (id: any, index: any) => {
        const { SET_DETAIL_CATEGORYTHIRDINDEX } = this.props
        SET_DETAIL_CATEGORYTHIRDINDEX(index)
        const global: any = window
        if (global.scrollTo) {
            global.scrollTo(0, 0)
        } else {
            global.screenTop = 0
        }
        this.index = 1
        this.categoryId = id
        this.flNode.finishLoad()
        this.getGoodsDataScrollLoad()
    }
    private handleTabView = () => {
        const { viewType } = this.state
        if (viewType === 'horizontal') {
            this.setState({
                viewType: 'vertical'
            })
        } else {
            this.setState({
                viewType: 'horizontal'
            })
        }
    }
    private goToUrl = (url: string = '/') => {
        const scrollTop = this.getScrollTop()
        window.sessionStorage.setItem('categoryTabsScrollTop', JSON.stringify(scrollTop))
        this.props.history.push(url)
    }
    private getScrollTop = () => {
        let scrollTop = 0
        if (document.documentElement && document.documentElement.scrollTop) {
            scrollTop = document.documentElement.scrollTop
        } else if (document.body) {
            scrollTop = document.body.scrollTop
        }
        return scrollTop
    }
}